<script lang="ts" setup>
import BaseButton from "@/components/BaseButton/index.vue";
import SelectFingerHostData from "@/components/SelectFingerHostData/index.vue";
import SelectHserverData from "@/components/SelectHserverData/index.vue";
import BaseUpDown from "@/components/BaseUpDown/index.vue";
import useSearch from "@/hooks/useSearch";
import useData from "./hooks/useData";
import { useUserStore } from "@/stores/modules/user";
import { formatDate } from "@/utils";
import { ElMessage } from "element-plus";

const { pageData, agrMap } = useData();
import {
  getCfgList,
  scfgEditDetail,
  scfgUpdate,
  scfgBatchFing,
  scfgBatchHserver
} from "@/api/modules/dynamic-camouflage/sentinel-config";
import { deleteData, getDataByPage, exportData, importData, downloadTemplate } from "@/api/modules/resource/sample-finger";
import UpdateForm from "./components/UpdateForm/index.vue";
import SelectResource from "./components/SelectResource/index.vue";
import moment from "moment";

interface Props {
  title?: string;
  rowData?: Object;
  links?: Object;
  ifid?: Object;
}

const props = withDefaults(defineProps<Props>(), {
  title: "配置节点",
  rowData: undefined,
  ifid: undefined,
  links: []
});
const userStore = useUserStore();
const username = computed(() => userStore.userInfo.name);
const { tableData, loadData, formData, reloadData } = useSearch({
  defaultData: {
    pageSize: 10
  },
  responseKey: {
    list: "data",
    total: "total"
  }
});
const emit = defineEmits(["update", "success"]);

function loadDataCb() {
  loadData({
    api: getCfgList,
    sendData: {
      curpage: formData.pageNum - 1,
      perpage: formData.pageSize,
      id: props.rowData?.id
    }
  });
}

function reloadDataCb() {
  reloadData();
  loadData({
    api: getCfgList,
    sendData: {
      curpage: formData.pageNum - 1,
      perpage: formData.pageSize,
      id: props.rowData?.id
    }
  });
}

/**删除*/
import useDelete from "@/hooks/useDelete";
import { computed, ref } from "vue";
import BaseCollapse from "@/components/BaseCollapse/index.vue";
import { Upload } from "@element-plus/icons-vue";
import useUpdate from "@/hooks/useUpdate";
import { requiredCheck, singleIpCheckFun, validatePortFun } from "@/utils/verify";
import { addData, editData } from "@/api/modules/dynamic-camouflage/sentinel-config";

const { deleteHandler, idList } = useDelete();

async function deleteCb(id) {
  await deleteHandler({
    api: deleteData,
    multiple: false,
    sendData: {
      id
    },
    hideMessageBox: false
  });
  loadDataCb();
}

function selectCb(data) {
  console.log(data);
  emit("update", data);
  idList.value = data.rowList.map(item => item.userId);
}

const urlDownload = function (url, name) {
  var a = document.createElement("a");
  // console.log(url)
  a.setAttribute("href", url);
  a.setAttribute("download", name);
  a.setAttribute("target", "_blank");
  const clickEvent = document.createEvent("MouseEvents");
  clickEvent.initEvent("click", true, true);
  a.dispatchEvent(clickEvent);
};

async function templateOperate(type) {
  if (type === "export") {
    const res = await exportData();
    console.info(res);
    const url = URL.createObjectURL(res);
    urlDownload(url, `finger_${moment().format("YYYYMMDDHHmmss")}.csv`);
  }
  if (type === "download") {
    const res = await downloadTemplate();
    console.info(res);
    const url = URL.createObjectURL(res);
    urlDownload(url, `finger_template_${moment().format("YYYYMMDDHHmmss")}.csv`);
  }
  if (type === "import") {
    const tempInput = document.createElement("input");
    tempInput.type = "file";
    tempInput.accept = ".xls,.xlsx,.csv";
    tempInput.click();
    tempInput.addEventListener("change", async () => {
      const res = await importData({ file: tempInput.files[0] });
      if (res.success) {
        ElMessage.success("导入成功");
        loadDataCb();
      } else {
        ElMessage.warning(res.msg);
      }
    });
  }
  // this.waitOperator();
}

const { updateFormData, updateFormRef, updateFormRules, submit, showHandle, openHandle, closeHandle } = useUpdate({
  rules: {
    ifid: [...requiredCheck("请选择线路")],
    name: [...requiredCheck("请输入区域名称")],
    vlanid: [...requiredCheck("请输入Vlan")],
    iprange: [
      ...requiredCheck("请输入IP"),
      {
        validator: (rule, value, callback) => {
          const testOne =
            /^(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\/(3[0-2]|[12]?[0-9])$/;
          const rangeRegex =
            /^((25[0-5]|2[0-4]\d|1\d{2}|[1-9]?\d)\.){3}(25[0-5]|2[0-4]\d|1\d{2}|[1-9]?\d)-((25[0-5]|2[0-4]\d|1\d{2}|[1-9]?\d)\.){3}(25[0-5]|2[0-4]\d|1\d{2}|[1-9]?\d)$/;

          if (value.includes("-") && !value.startsWith("-")) {
            console.log("rangeRegex.test(value)::", rangeRegex.test(value));
            const ipOne = value.split("-")[0];
            const ipTwo = value.split("-")[1];

            function ipToInt(ip) {
              return ip.split(".").reduce((acc, octet) => (acc << 8) + parseInt(octet, 10), 0);
            }

            if (rangeRegex.test(value) && ipToInt(ipOne) <= ipToInt(ipTwo)) {
              callback();
            } else {
              callback("IP格式错误");
            }
          }
          if (value.includes("/")) {
            if (testOne.test(value)) {
              callback();
            } else {
              callback("IP格式错误");
            }
          }
          if (singleIpCheckFun(value)) {
            callback();
          } else {
            callback("IP格式错误");
          }
        }
      }
    ],
    destport: [
      ...requiredCheck("请输入端口"),
      {
        validator: (rule, value, callback) => {
          if (value.includes(";") && !value.startsWith(";")) {
            const ports = value.split(";");
            const pass = ports.every(port => validatePortFun(port));
            if (pass) {
              callback();
            } else {
              callback("端口格式错误");
            }
          }
          if (value.includes("-") && !value.startsWith("-") && !value.endsWith("-")) {
            const ports = value.split("-");
            let startPort = ports[0];
            let endPort = ports[1];
            const pass = ports.every(port => validatePortFun(port));
            if (pass && Number(startPort) < Number(endPort)) {
              callback();
            } else {
              callback("端口格式错误");
            }
          }
          if (validatePortFun(value)) {
            callback();
          } else {
            callback("端口格式错误");
          }
        }
      }
    ]
  },
  defaultData: {
    type: "1"
  }
});

async function submitCb() {
  let ifid = updateFormData.ifid;
  await submit({
    addApi: addData,
    updateApi: editData,
    sendData: {
      destport: updateFormData.destport,
      ifid: updateFormData.ifid,
      iprange: updateFormData.iprange,
      name: updateFormData.name,
      type: updateFormData.type,
      vlanid: updateFormData.vlanid,
      cfg: updateFormData?.id ? '{"interval":0,"percent":0}' : undefined,
      id: updateFormData?.id
    }
  });
  emits("success", ifid);
}

function openCb() {
  openHandle({
    row: {
      ...props.rowData
    },
    id: props.rowData?.id
  });
  if (props.ifid) {
    updateFormData.ifid = props.ifid;
  }
  loadDataCb();
}

const showEditActive = ref("");
const editValue = ref("");
const editInput = ref(null);

function setShowEditActive(type, index) {
  showEditActive.value = type + "-" + index;
  if (type === "hostname") {
    editValue.value = tableData.list[index].hostname;
  }
  if (type === "mac") {
    editValue.value = tableData.list[index].mac;
  }
  setTimeout(() => {
    editInput.value.focus();
  }, 100);
}

function editActiveBlur(type, index) {
  if (type === "hostname") {
    if (editValue.value === tableData.list[index].hostname) {
      showEditActive.value = "";
      return;
    }
  }
  if (type === "mac") {
    if (editValue.value === tableData.list[index].mac) {
      showEditActive.value = "";
      return;
    }
  }
  updateData(type, index);
}

async function updateData(type, index) {
  const detail = await scfgEditDetail({
    id: tableData.list[index].id
  });

  console.log(detail);
  if (type === "mac") {
    await scfgUpdate({
      id: tableData.list[index].id,
      ifid: updateFormData.ifid,
      fingerip: detail.fingerip,
      srvid: "1,2",
      hostname: detail.hostname,
      mac: editValue.value
    });
  }
  if (type === "hostname") {
    await scfgUpdate({
      id: tableData.list[index].id,
      ifid: updateFormData.ifid,
      fingerip: detail.fingerip,
      srvid: "1,2",
      hostname: editValue.value,
      mac: detail.mac
    });
  }
  showEditActive.value = "";
  ElMessage.success("更新成功");
  loadDataCb();
}

async function selectFinger(data, id) {
  console.log(data);
  const fingerips = data.rowList.map(item => item.ip);
  await scfgBatchFing({
    id,
    fingerip: fingerips.join(),
    ifid: updateFormData.ifid,
    interval: 0
  });
  ElMessage.success("更新成功");
  loadDataCb();
}

// 选择高交
async function selectHs(data, id) {
  console.log(data);
  const hs = data.map(item => item.id);
  await scfgBatchHserver({
    id,
    srvid: hs.join(),
    ifid: updateFormData.ifid
  });
  ElMessage.success("更新成功");
  loadDataCb();
}
</script>

<template>
  <div class="update-form" style="display: inline-block" @click="openCb">
    <slot>
      <el-button type="primary">新增</el-button>
    </slot>
  </div>
  <base-dialog @confirm="showHandle = false" width="1050px" :title="title" v-if="showHandle" v-model="showHandle">
    <div class="details">
      <div class="details-main">
        <div style="padding: 16px">
          <he-table
            @handle-current-change="loadDataCb"
            :total="tableData.total"
            v-model:page-size="formData.pageSize"
            v-model:page-num="formData.pageNum"
            operate-width="180px"
            :operate-list="[]"
            :table-data="tableData.list"
            :column-data="pageData.columnData"
            :show-multiple="false"
            :show-summary="false"
            :show-operate="false"
            :show-multiple-column="false"
            :show-pagination="true"
            @select="selectCb"
          >
            <template #8Default="{ data }">
              {{ formatDate(data.row[8]) }}
            </template>
            <template #macDefault="{ data }">
              <div v-if="showEditActive === `mac-${data.$index}`">
                <el-input
                  ref="editInput"
                  v-model="editValue"
                  @blur="editActiveBlur('mac', data.$index)"
                  placeholder="请输入"
                ></el-input>
              </div>
              <div v-else class="h-box justify-center">
                <span class="clip-text" style="max-width: 100px">
                  {{ data.row.mac }}
                </span>
                <el-icon @click="setShowEditActive('mac', data.$index)" class="cursor-pointer mg-l-sm">
                  <EditPen />
                </el-icon>
              </div>
            </template>
            <template #hostnameDefault="{ data }">
              <div v-if="showEditActive === `hostname-${data.$index}`">
                <el-input
                  ref="editInput"
                  v-model="editValue"
                  @blur="editActiveBlur('hostname', data.$index)"
                  placeholder="请输入"
                ></el-input>
              </div>
              <div v-else class="h-box justify-center">
                <span class="clip-text" style="max-width: 100px">
                  {{ data.row.hostname }}
                </span>
                <el-icon @click="setShowEditActive('hostname', data.$index)" class="cursor-pointer mg-l-sm">
                  <EditPen />
                </el-icon>
              </div>
            </template>
            <template #fingeripDefault="{ data }">
              <SelectFingerHostData
                :maxMultipleNum="1"
                :defaultSelect="data.row.fingerip"
                @select="d => selectFinger(d, data.row.id)"
              >
                <el-icon class="cursor-pointer">
                  <Document />
                </el-icon>
              </SelectFingerHostData>
            </template>
            <template #srvidDefault="{ data }">
              <SelectHserverData  :defaultSelect="data.row.srvid" @select="d => selectHs(d, data.row.id)">
                <el-icon class="cursor-pointer">
                  <Document />
                </el-icon>
              </SelectHserverData>
            </template>
            <template #resourceDefault="{ data }">
              <SelectResource
                @success="loadDataCb"
                :defaultSelectFinger="data.row.fingerip"
                :defaultSelectSrvid="data.row.srvid"
                :row-data="{
                  id: data.row.id,
                  ifid: updateFormData.ifid
                }"
              >
                <el-icon class="cursor-pointer">
                  <Document />
                </el-icon>
              </SelectResource>
            </template>
            <template #operationDefault="{ data }">
              <UpdateForm
                :row-data="{
                  ...data.row
                }"
                :title="`编辑`"
                @success="loadDataCb"
              >
                <base-button type="edit_text"></base-button>
              </UpdateForm>
              <base-button @click="deleteCb(data.row.id)" type="del_text"></base-button>
            </template>
          </he-table>
        </div>
      </div>
    </div>
    <template #footer-more-button></template>
  </base-dialog>
</template>
<style scoped lang="scss">
.clip-text {
  max-width: 100px;

  overflow-x: hidden;

  display: inline-block;

  text-overflow: clip;

  overflow: hidden;

  text-overflow: ellipsis;
}
</style>
